package com.github.bobjoy.java.spi;

import com.github.bobjoy.java.spi.plugin.Plugin;

import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ServiceLoader;

/**
 * 学习地址：http://blog.csdn.net/huxu981598436/article/details/78557566
 */
public class SPIDemo {

    /**
     * 动态加载实现 jar
     */
    private static void loadSpiImplJar( ) {
        try {

            // 通过反射获取加载器 addURL 方法
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);

            // 获取系统类加载器
            URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

            // 读取插件实现列表
            BufferedReader reader = new BufferedReader(new FileReader("E:\\workspaces\\study\\java-learning\\spi\\spi.txt"));

            // 循环加载插件 jar
            String url;
            while ((url = reader.readLine()) != null) {
                if (url.startsWith("file:///")) {
                    method.invoke(classLoader, new URL(url));
                }
            }

        } catch (Exception e) {
            System.out.println("加载jar包失败！" + e.getMessage());
        }
    }

    public static void main(String[] args) {

        // 动态加载Jar包
        loadSpiImplJar();

        ServiceLoader<Plugin> loaders = ServiceLoader.load(Plugin.class);
        for (Plugin service : loaders) {
            System.out.println(service.sayHello());
        }

    }
}
